﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using System.Web.UI.HtmlControls;
using ECommerce.Library;
using ECommerce.Library.ECommerce;
using System.Text;
using ECommerce.Library.Web;
using eShop.Model;
using eShop.Business;

public partial class controls_wucProductDetails : System.Web.UI.UserControl
{
    public String SupplierId
    {
        get
        {
            try
            {
                return Page.RouteData.Values["partnerId"].ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    public String ProductPath
    {
        get
        {
            try
            {
                return Page.RouteData.Values["path"].ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    public int ProductId
    {
        get
        {
            return Convert.ToInt32(this.ViewState["_PRODUCTID"]);
        }
        set
        {
            this.ViewState["_PRODUCTID"] = value;
        }
    }

    ShoppingCart _shoppingCart;
    ReadWriteCustomCollection<Favorites> _favorites;

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void BindDetails()
    {
        LoadProductData();
        LoadProductAdditionalData();
        if (!Page.IsPostBack)
        {
            LoadSession();
        }
    }

    private void LoadProductAdditionalData()
    {
        IList<TblProductAdditionalImage> additionalImages = TblProductAdditionalImage.GetTblProductAdditionalImageByProductID(ProductId);

        //rptAdditionalViews.DataSource = additionalImages;
        //rptAdditionalViews.DataBind();

        rptGalleryLinks.DataSource = additionalImages;
        rptGalleryLinks.DataBind();

        Product product = Product.Load(ProductId);
        ReadWriteCustomCollection<Product> relatedProducts = Product.RelatedProducts(1000, product.Category.CategoryId, product.ProductId);
        if (relatedProducts != null && relatedProducts.Count > 0)
        {
            rprProductLikes.DataSource = relatedProducts;
            rprProductLikes.DataBind();
            dvRelatedProducts.Visible = true;
        }
        else
        {
            dvRelatedProducts.Visible = false;
        }
    }

    protected void rprProductLikes_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Product product = (Product)e.Item.DataItem;
            if (product != null)
            {
                HtmlImage imgAdditionalImage = (HtmlImage)e.Item.FindControl("imgAdditionalImage");
                Label lblProductName = (Label)e.Item.FindControl("lblProductName");
                HtmlAnchor lnkProduct = (HtmlAnchor)e.Item.FindControl("lnkProduct");
                HtmlAnchor lnkProductNameLink = (HtmlAnchor)e.Item.FindControl("lnkProductNameLink");

                string productName = product.ProductName;
                lblProductName.ToolTip = productName;
                if (productName.Length > 20)
                    productName = String.Format("{0}...", productName.Substring(0, 12));
                lblProductName.Text = productName;

                string imageUrl = ImageResizer.CheckImageMissing(product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageDetailSizeUrl);
                if (imageUrl.Contains("~"))
                    imageUrl = ResolveUrl(imageUrl);
                imgAdditionalImage.Src = imageUrl;

                lnkProduct.HRef = Page.ResolveUrl(product.ProductUrl);
                lnkProductNameLink.HRef = Page.ResolveUrl(product.ProductUrl);
            }
        }

    }
    private void LoadProductData()
    {
        Product product = null;
        if (!string.IsNullOrEmpty(SupplierId))
            product = Product.Load(ProductPath, SupplierId);
        else
            product = Product.Load(ProductPath);
        ProductId = product.ProductId;

       // Page.ClientScript.RegisterStartupScript(typeof(Page), "_MENU_TOGGLE", String.Format("ToggleChildVisibility({0});", product.Category.ParentCategoryId), true);
       // Page.ClientScript.RegisterStartupScript(typeof(Page), "_SELECTCATMENU", String.Format("SetCurrentCategory({0});", product.Category.CategoryId), true);

        this.AddProductToRecentlyViewedProducts(product);

        lblPrice.Text = Utility.FormatPriceText(product.ProductPrice);
       
        lblProductName.Text = product.ProductName;
       
        lblAtGlance.Text = Server.HtmlDecode(product.ProductDescription);
        
       
        lblItemNo.Text = product.ItemNumber;
        ProductStock stock = product.Stocks[0];
        lblWeight.Text = Convert.ToString(stock.Weight) + " lbs ";
        if (!string.IsNullOrEmpty(stock.WeightUnit))
        {
            if (Convert.ToDecimal(stock.WeightUnit) > 0)
            {
                lblWeightUnit.Text = Convert.ToString(stock.WeightUnit) + " oz.";
            }
            else
            {
                lblWeightUnit.Text = "0" + "Oz.";
            }
        }
        lblSize.Text = stock.Size;
        rptSiteMap.DataSource = CategoryManager.GetSubCategorySiteMapTree(SiteUtility.SuperRootCategoryId, product.Category.CategoryId);
        rptSiteMap.DataBind();

        hlkProductLink.Text = product.ProductName;
        System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(product.ProductImageDetailSize);
        if (originalImageDimension.Width > 250)
        {
            imgProductDetailImage.Style.Add("width", "250px;");
        }
        else if (originalImageDimension.Height > 200)
        {
            imgProductDetailImage.Style.Add("height", "200px;");
        }
        imgProductDetailImage.Src = String.Format("{0}_services/getListingThumb.aspx?file={1}&w=274&h=323", SiteGlobals.BaseUrl, ImageResizer.CheckImageMissing(product.ProductImageDetailSize, AutoGear.BLL.SiteSettings.NoImageDetailSizeUrl));
        lnkEnlargeImage.HRef = String.Format("{0}?KeepThis=true&TB_iframe=true", ImageResizer.CheckImageMissing(product.ProductImageMaxSize, AutoGear.BLL.SiteSettings.NoImageMaxSizeUrl));
        
      
        LoadReviews();
    }

    private void LoadReviews()
    {
        ECommerce.DAL.CustomCollection<TblProductReview> review = TblProductReview.GetTblProductReviewByProductId(ProductId);
        StringBuilder reviewsHtml = new StringBuilder();
        if (review != null && review.Count > 0)
        {
            int countRating = 0;

            ReviewCount.Text = review.Count.ToString();
            for (int i = 0; i < review.Count; i++)
            {
                countRating = countRating + Convert.ToInt32(review[i].RatingValue);
            }
            //rptReviews.DataSource = review;
            //rptReviews.DataBind();

            //countRating = Convert.ToInt32(countRating / review.Count);
            //litReviewAvg.Text = countRating.ToString();
            //Rating.CurrentRating = countRating;
        }
        else
        {
            
        }
    }

    protected void rptReviews_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TblProductReview currentReview = (TblProductReview)e.Item.DataItem;
            if (currentReview != null)
            {
                AjaxControlToolkit.Rating ReviewRating = (AjaxControlToolkit.Rating)e.Item.FindControl("ReviewRating");
                ReviewRating.CurrentRating = Convert.ToInt32(currentReview.RatingValue);
            }
        }
    }

    private void AddProductToRecentlyViewedProducts(Product product)
    {
        List<Product> recentProducts = AutoGearSessionManager.RecentlyViewedProducts;

        if (recentProducts != null && recentProducts.Count > 0)
        {
            recentProducts.RemoveAll(delegate(Product p) { return p.ProductId.Equals(product.ProductId); });
        }

        recentProducts.Add(product);

        AutoGearSessionManager.RecentlyViewedProducts = recentProducts;
    }

    protected ReadWriteCustomCollection<KeyValuePair<string, string>> GetDefaultSiteMap()
    {
        ReadWriteCustomCollection<KeyValuePair<string, string>> node = new ReadWriteCustomCollection<KeyValuePair<string, string>>();
        node.Add(new KeyValuePair<string, string>("Home", AutoGear.BLL.CustomSiteMap.Home));
        node.Add(new KeyValuePair<string, string>("Products", AutoGear.BLL.CustomSiteMap.Products));
        return node;
    }


    protected void rptSiteMap_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                HyperLink hlkSiteMap = (HyperLink)e.Item.FindControl("hlkSiteMap");
                KeyValuePair<string, string> node = (KeyValuePair<string, string>)e.Item.DataItem;
                hlkSiteMap.NavigateUrl = node.Value;
                hlkSiteMap.Text = node.Key.ToLower() == "none" ? "Home" : node.Key;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void imbAddToCart_Click(object sender, EventArgs e)
    {
        int qty;
        int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
        string strMetalType = string.Empty;
        string strGiftWrapper = string.Empty;
        Product product = Product.Load(ProductId);
        if (qty > 0)
        {

            this.AddCartItemToShoppingCart(qty, product, strMetalType, strGiftWrapper);
            lblMsgProductName.Text = product.ProductName;
            if (product.StandardCost > 0)
            {
                lblMsgPrice.Text = Utility.FormatPriceText(product.StandardCost + product.AdditionalPrice);
            }
            else
            {
                lblMsgPrice.Text = Utility.FormatPriceText(product.ProductPrice + product.AdditionalPrice);
            }
            lblMsgQuantity.Text = tbxQuantity.Text;
            lblMsgTotal.Text = AutoGearSessionManager.ShoppingCart.TotalCartItem + AutoGearSessionManager.ShoppingCart.TotalGiftItem + " Items";
            LoadSession();

            //UpdatePanel upnlShoppingBasket = (UpdatePanel)this.Page.Master.FindControl("upnlShoppingBasket");
            //Literal litShoppingCartTotal = (Literal)upnlShoppingBasket.FindControl("litShoppingCartTotal");
            double grandTotal = AutoGearSessionManager.ShoppingCart.SubTotal + AutoGearSessionManager.ShoppingCart.GiftSubTotal;
            //litShoppingCartTotal.Text = string.Format("{0:c}", grandTotal);
            //upnlShoppingBasket.Update();

            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "_showblockui", "ShowConfirm(true);", true);
            imbCheckout.Visible = true;
        }
        else
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "_showblockui", "ShowConfirm(false);", true);
        }
    }
    protected void AddCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
        CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
        shoppingcart.AddCartItem(cartItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
    }


    protected void rptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;
            if (cartItem.Product.ProductId > 0)
            {

                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                hlkItem.NavigateUrl = cartItem.Product.ProductUrl;
                hlkItem.Text = cartItem.Product.ProductName;

                Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
                imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(cartItem.Product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.ProductPrice);

                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                lblItemNumber.Text = "Item Number: " + cartItem.Product.ItemNumber;

                Label lblMetalType = (Label)e.Item.FindControl("lblMetalType"); //+++ 062610
                lblMetalType.Text = "Class Type: " + cartItem.MetalType.ToString(); //+++ 062610


                Label lblGiftWrapper = (Label)e.Item.FindControl("lblGiftWrapper"); //+++ 062610
                lblGiftWrapper.Text = "Free gift wrap: " + cartItem.GiftWrapper.ToString(); //+++ 062610

                Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
                lblQuantity.Text = cartItem.Quantity.ToString();

            }

        }

    }

    protected void LoadSession()
    {
        _shoppingCart = AutoGearSessionManager.ShoppingCart;
        _favorites = AutoGearSessionManager.FavoritesList;
    }

    protected void imbCheckout_Click(object sender, EventArgs e)
    {
        if (SessionManager.IsUserLoggedIn)
        {
            AutoGearSessionManager.CheckoutSteps = CheckoutSteps.PreCheckout;
            Response.Redirect(CustomSiteMap.ShoppingCart);
        }
        else
        {
            AutoGearSessionManager.CheckoutSteps = CheckoutSteps.ShoppingCart;
            Response.Redirect(CustomSiteMap.ShoppingCart);
        }
    }
    protected void lnkAddToWishList_Click(object sender, EventArgs e)
    {
        try
        {
            if (SessionManager.IsUserLoggedIn)
            {
                TblProductWishList wishList = new TblProductWishList();
                wishList.ProductId = ProductId;
                wishList.SystemUserId = SessionManager.LoggedUser.UserId;
                wishList.Save();
                if (wishList.ProductWishListId != 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowWishList('Successfully added to your wishlist');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowWishList('Already exists in your wishlist');", true);
                }

            }
            else
            {
                Response.Redirect("~/login.aspx?ReturnUrl=" + Server.UrlEncode(Request.Path));
            }
            //BindInfo();
        }
        catch (Exception ex)
        {

        }
    }
    protected void btnSaveReview_Click(object sender, EventArgs e)
    {
        int lastReviewId = SaveReview();
        LoadReviews();

        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "_HIDEREVIEWMODAL", "$.modal.close(); $('#tabs').tabs('select', 2);", true);
        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "_PENDINGALERT", "ShowAlert('<b>Your review is pending administrator approval and will be published once it is approved.<b>', 'Notification');", true);
        Email.SendGenericEmail("Admin", SiteSettings.AdminEmail, "New Review Pending Moderation", String.Format("A new product review has been submitted. Please visit the following link <a href='" + SiteGlobals.BaseUrl + "admin/product-review-edit.aspx?rid={1}'>{0}admin/product-review-edit.aspx?rid={1}</a> to approve/disapprove.", SiteGlobals.BaseUrl, lastReviewId));
    }
    private int SaveReview()
    {
        TblProductReview newReview = new TblProductReview();
        newReview.ProductId = ProductId;
        newReview.CustomerName = txtReviewerName.Text;
        newReview.CustomerEmail = txtReviewerEmail.Text;
        newReview.ReviewText = Server.HtmlEncode(txtComment.Text.Replace("\n", "<br />"));
        newReview.RatingValue = Convert.ToInt32(Session["_lastRatingValue"].ToString());
        newReview.ReviewDate = DateTime.Now;
        newReview.IsApproved = false;
        return TblProductReview.CreateNewTblProductReview(newReview);
    }
    protected void Rating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
        Session["_lastRatingValue"] = e.Value;
    }
}